<?php

class Customer extends WebService_base{
	var $customer_id;
	var $sid;
	var $first_name;
	var $last_name;
	var $email;
	var $cart;
	
	/**
	 * Constructor
	 *
	 */	
	function __construct(){
		parent::__construct();
		if($this->ws_get_config()){
			$GLOBALS['db_link'] = $this->db_connect();
		}
		$this->customer_id = 0;
		$this->sid = session_id();
		if(isset($_SESSION[customer_id])){
			$this->customer_id = $_SESSION[customer_id];
			$_SESSION[cart][customer_id] = $_SESSION[customer_id];
		}
		if(isset($_SESSION[cart][customer_id])){
			$this->customer_id = $_SESSION[cart][customer_id];
			$_SESSION[customer_id] = $_SESSION[cart][customer_id];
		}
		$this->first_name = null;
		$this->last_name = null;
		$this->email = null;
		$this->cart = null;		
	}

	/**
	 * Adds a new customer based on the provided information
	 *
	 * @param string $first_name
	 * @param string $last_name
	 * @param string $address
	 * @param string $address2
	 * @param string $city
	 * @param string $state
	 * @param string $zip
	 * @param string $email
	 * @param string $email2
	 * @param string $dob
	 * @param string $gender
	 * @param string $phone
	 * @param string $company
	 * @param string $fax
	 * @param string $phone2
	 * @param string $password
	 * @return mixed
	 */
	function AddCustomer($first_name, $last_name, $address, $address2, $city, $state, $zip, $email, $email2, $dob, $gender, $phone, $company, $fax, $phone2, $password){
		$form_vars[first_name] = $first_name;
		$form_vars[last_name] = $last_name; 
		$form_vars[address1] = $address;
		$form_vars[address2] = $address2;
		$form_vars[city] = $city;
		$form_vars[state] = $state;
		$form_vars[zip] = $zip;
		$form_vars[email] = $email;
		$form_vars[email2] = $email2;
		$form_vars[birthdate] = date('Y-m-d H:i:s',strtotime($dob));
		$form_vars[gender] = $gender;
		$search = array('-', '(', ')'); 
		$replace = array('','','');
		$form_vars[phone] = str_replace($search, $replace, $phone);
		$form_vars[company] = $company;
		$form_vars[fax] = str_replace($search, $replace, $fax);
		$form_vars[phone2]= str_replace($search, $replace, $phone2);
		$form_vars[password] = $password;

		$first_name = tep_db_prepare_input($form_vars[first_name]); 
		$last_name = tep_db_prepare_input($form_vars[last_name]);
		$address = tep_db_prepare_input($form_vars[address1]);
		$address2 = tep_db_prepare_input($form_vars[address2]);
		$city = tep_db_prepare_input($form_vars[city]);
		$state = tep_db_prepare_input($form_vars[state]);
		$zone = tep_db_fetch_array(tep_db_query("SELECT zone_id FROM zones WHERE zone_code = '$state'"));
		$state = $zone[zone_id];
		$zip = tep_db_prepare_input($form_vars[zip]);
		$email = tep_db_prepare_input($form_vars[email]);
		$email2 = tep_db_prepare_input($form_vars[email2]);
		$dob = tep_db_prepare_input($form_vars[birthdate]);
		$gender = tep_db_prepare_input($form_vars[gender]); 
		$phone = tep_db_prepare_input($form_vars[phone]);
		$company = tep_db_prepare_input($form_vars[company]);
		$fax = tep_db_prepare_input($form_vars[fax]);
		$phone2 = tep_db_prepare_input($form_vars[phone2]);
		$encryption = (defined('ENCRYPTION_STYLE'))?ENCRYPTION_STYLE:'O';
		$password = tep_encrypt_password($form_vars[password], $encryption);

		$check = $this->CustomerEmail($email);
		if(isset($check[customers_id])){
			return array('Error'=>'The provided e-mail is already registered.');
		}
		
		$tbl_addressBook = TABLE_ADDRESS_BOOK;
		$tbl_customers = TABLE_CUSTOMERS;
		$tbl_customersInfo = TABLE_CUSTOMERS_INFO;

		$customersInsert  = "INSERT INTO $tbl_customers (customers_firstname,customers_lastname,customers_email_address,customers_fax,customers_password, encryption_style,customers_second_email_address,customers_telephone,customers_second_telephone,customers_gender,customers_dob) "; 
		$customersInsert .= "values('$first_name', '$last_name', '$email', '$fax','$password', '$encryption', '$email2', '$phone', '$phone2', '$gender', '$dob')";
		$qr = tep_db_query($customersInsert);
		$customersSelectID = "SELECT customers_id FROM $tbl_customers WHERE customers_dob = '$dob' AND customers_email_address = '$email'";

		$cSIresult = tep_db_fetch_array(tep_db_query($customersSelectID));

		$customer_id = $cSIresult[customers_id];
		$this->customer_id = $customer_id;
		
		$this->first_name = $first_name;
		$this->last_name = $last_name;
		$this->email = $email;
		$_SESSION[customer_id] = $this->customer_id;
		$_SESSION[cart][customer_id] = $this->customer_id;
		
		$addressInsert  = "INSERT INTO $tbl_addressBook (customers_id, entry_firstname, entry_lastname, entry_street_address, entry_postcode, entry_city, entry_country_id, entry_gender, entry_zone_id, entry_company) "; 
		$addressInsert .= "VALUES ('$customer_id','$first_name','$lastname','$address','$zip','$city','223','$gender','$state', '$company')";
		$qr = tep_db_query($addressInsert);
		
		$addressSelectID = "SELECT address_book_id FROM $tbl_addressBook WHERE customers_id = '$customer_id'";
		$aIresult = tep_db_fetch_array(tep_db_query($addressSelectID));
		$address_book_id = $aIresult[address_book_id];

		$customersUpdateDefaultAddress = "UPDATE $tbl_customers set customers_default_address_id = '$address_book_id' WHERE customers_id = '$customer_id'";

		$qr = tep_db_query($customersUpdateDefaultAddress);
		$InfoInsert = "INSERT INTO $tbl_customersInfo (customers_info_id, customers_info_number_of_logons, customers_info_date_account_created, customers_info_source_id, customers_info_date_account_last_modified) values ('$customer_id', '0', now(), '5', now())";		
		$qr = tep_db_query($InfoInsert);
		$error = $this->MigrateCart();

		$myReturn = array($customer_id, $address_book_id, $this->first_name, $error);
		return $myReturn;
	}

	/**
	 * Customer Login
	 *
	 * @param string $password
	 * @param string $email
	 * @return mixed
	 */
	function Login($password = null, $email = null){
		$credentials = $this->Credentials($email, $password);
		if(!is_array($credentials[ERROR])){
			$this->email = $credentials[email_address];
			$this->password = $credentials[password];
		}
		else
			return $credentials;

		$customer_details = $this->CustomerEmail($this->email);
		
		if($this->CustomerPassword($customer_details, $credentials[password])){
			$this->customer_id = $customer_details[customers_id];
			$this->first_name = $customer_details[customers_firstname];
			$this->last_name = $customer_details[customers_lastname];
			$this->email = $customer_details[customers_email_address];
			$_SESSION[customer_id] = $this->customer_id;
			$this->MigrateCart();
			return array('customer_id'=>$this->customer_id);
		}
		else {
			unset($customer_details);
			$customer_details = array('ERROR'=> 'The e-mail address, or login ID, and password are not valid'); 
			return $customer_details;
		}
	}
	
	/**
	 * Credentials takes raw input from user and prepares it for the authentication process
	 *
	 * @param string $rawEmail
	 * @param string $rawPass
	 * @return mixed
	 */	
	private function Credentials($rawEmail = null, $rawPass = null){
		if (isset($rawEmail) && ($rawPass)) {
			$email_address = tep_db_prepare_input($rawEmail);
    		$password = tep_db_prepare_input($rawPass);
    		$return = array('email_address'=>$email_address, 'password'=>$password);
		} 	
		else
			$return = array('ERROR'=>'You must supply a login and password.');

		return $return;	
	}

	/**
	 * test for valid e-mail address
	 *
	 * @param string $email_address
	 * @return mixed
	 */
	private function CustomerEmail($email_address){
		if($this->ws_get_config()){
			$GLOBALS['db_link'] = $this->db_connect();
		}
		else
			$GLOBALS['db_link'] = tep_db_connect(); 
		$add_option="";
		if (ACCOUNT_USERNAME=="true") 
			$add_option=" or customers_username='" . tep_db_input($email_address) . "'";
		$query = "select customers_id, customers_firstname, customers_lastname, customers_password, customers_email_address, customers_default_address_id,encryption_style from " . TABLE_CUSTOMERS . " where customers_email_address = '" . tep_db_input($email_address) . "' " . $add_option;
		$check_customer_query = tep_db_query($query);
		if (tep_db_num_rows($check_customer_query)) {
			$return = tep_db_fetch_array($check_customer_query);
		}
		else{
			$return = array('ERROR'=>'No user has registered the provided E-mail Address');
		}
		return  $return;
	}	
	
	/**
	 * Check Customer password
	 * 
	 * @param mixed $check_customer
	 * @param string $password
	 * @return bool
	 */
	private function CustomerPassword($check_customer = array(),$password = null){
		 if (!tep_validate_password($password, $check_customer['customers_password'],$check_customer['encryption_style']))
		 	return false;
		 else 
		 	return true;
	}
	/**
	 * moves all content from temp cart to customer cart based on Session id and customer id
	 *
	 * @return mixed
	 */
	private function MigrateCart(){
		$customer_id = $this->customer_id;
		$link = $this->db_connect();
		$error = array();
		$error[] = array('hello' => 'world');
		//Move Contents of guest cart to Customer's shopping cart
		$SESSIONS_TABLE = TABLE_CUSTOMERS_TEMP_BASKET_SESSIONS;
		$BASKET_TABLE = TABLE_CUSTOMERS_TEMP_BASKET;		
		$tempSessionSelect = "SELECT * FROM " . $SESSIONS_TABLE . " WHERE customers_id = '". session_id() ."'";
		$tempBasketSelect = "SELECT * FROM " . $BASKET_TABLE . " WHERE customers_id =  '". session_id() ."'";		
		$tBSresult = $this->db_query($tempBasketSelect, $link);
		$error[] = array($this->db_num_rows($tBSresult), $tempBasketSelect);
		$tSSresult = $this->db_query($tempSessionSelect, $link);
		$error[] = array($this->db_num_rows($tSSresult), $tempSessionSelect);
		if($this->db_num_rows($tSSresult)>0){
			$SESSIONS_TABLE = TABLE_CUSTOMERS_BASKET_SESSIONS;
			$BASKET_TABLE = TABLE_CUSTOMERS_BASKET;			
			while($row = $this->db_fetch_array($tSSresult)){
				$Ssql = "insert into ". $SESSIONS_TABLE ." (customers_id,products_id,session_id,session_type,session_group,session_date) "; 
				$Ssql .= " values ('$customer_id','$row[products_id]','$row[session_id]','$row[session_type]','$row[session_group]','$row[session_date]')";
				$sessions_inserts[] = $sql;						
			}
			while($row = $this->db_fetch_array($tBSresult)){
				$Bsql = "insert into " . $BASKET_TABLE; 
				$Bsql .= " (customers_id, products_id, customers_basket_quantity, customers_basket_date_added,products_type,old_orders_id,answer_type,answer_value) ";
				$Bsql .= "values ('$customer_id', '$row[products_id]', '$row[customers_basket_quantity]', now(),'$row[products_type]','$row[old_orders_id]','$row[answer_type]','$row[answer_value]')";
				$basket_inserts[] = $Bsql;
			}				
			foreach($basket_inserts as $insert){
				$result = $this->db_query($insert,$link);
				$error[] = array($this->db_num_rows($result), $insert);
			}
			foreach($sessions_inserts as $insert){
				$result = $this->db_query($insert,$link);
				$error[] = array($this->db_num_rows($result), $insert);
			}
			$SESSIONS_TABLE = TABLE_CUSTOMERS_TEMP_BASKET_SESSIONS;
			$BASKET_TABLE = TABLE_CUSTOMERS_TEMP_BASKET;		
			$sql = "DELETE FROM " . $SESSIONS_TABLE . " WHERE customers_id =  '". session_id() ."'";
			$result = $this->db_query($sql, $link);
			$error[] = array($this->db_num_rows($result), $sql);
			$sql = "DELETE FROM " . $BASKET_TABLE . " WHERE customers_id =  '". session_id() ."'";
			$result = $this->db_query($sql, $link);
			$error[] = array($this->db_num_rows($result), $sql);
			return $error;				
		}
		return $error;
	}

}



?>